package com.hanhai.material.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hanhai.material.device.entity.*;
import com.hanhai.material.device.service.SysWeightDataService;
import com.hanhai.material.device.service.SysWeightPlcService;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.hanhai.material.device.entity.table.SysWeightPlcTableDef.SYS_WEIGHT_PLC;

@Component
@Log4j2
public class AutoGetDataUtils {
    @Autowired
    SysWeightPlcService sysWeightPlcService;

    @Autowired
    SysWeightDataService sysWeightDataService;

    public String getSid() {
        String username = "schanhai";
        String password = "Hh123456.";
        RestTemplate restTemplate = new RestTemplate();
        String baseUrl = "https://api.123321yun.com/api/user/login/?username=%s&password=%s";
        String url = String.format(baseUrl, username, password);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
//        headers.set("Authorization", authorization);
        HttpEntity httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, httpEntity, Object.class);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(responseEntity.getBody());
        System.out.println("JSON:" + jsonObject);
        String sid = jsonObject.getString("data");
        return sid;
    }

    public SysWeightData getWeightData(SysProductRecord sysProductRecord) {
        String sid = this.getSid();
        System.out.println("Sid:" + sid);
        RestTemplate restTemplate = new RestTemplate();
        String machineArea = sysProductRecord.getMachineArea().split("区域")[0];
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_WEIGHT_PLC.NAME.eq(machineArea));
        queryWrapper.limit(1);
        SysWeightPlc sysWeightPlc = this.sysWeightPlcService.getOne(queryWrapper);

        String plcDeviceId = String.valueOf(sysWeightPlc.getDeviceId());
        String baseUrl = "https://api.123321yun.com/device/ex/getDetail?deviceId=%s";
        String url = String.format(baseUrl, plcDeviceId);
        System.out.println("Url:" + url);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        headers.set("__sid", sid);
        HttpEntity httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, httpEntity, Object.class);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(responseEntity.getBody());
        System.out.println("Result:" + jsonObject);
        long sleepTime = 10;
        if (jsonObject.getString("code").equals("200.0")) {
            SysPlc sysPlc = jsonObject.getObject("data", SysPlc.class);
            log.error("SYSPLC:{}", sysPlc);
            JSONArray jsonObject1 = JSON.parseArray(sysPlc.getParamsUp());
            List<SysWeightData> sysWeightDataList = new ArrayList<>();
            for (Object object : jsonObject1) {
                SysWeightData sysWeightData = new SysWeightData();
                Paramsup paramsup = JSONObject.parseObject(JSONObject.toJSONString(object), Paramsup.class);
                String machineNo = paramsup.getName().split("#")[0];
                if (machineNo.length() == 1) {
                    machineNo = "0" + machineNo;
                }
                String machineName = sysWeightPlc.getName() + machineNo;
                sysWeightData.setMachineName(machineName);
                sysWeightData.setNum(BigDecimal.valueOf(Double.parseDouble(paramsup.getValue()) ));
                sysWeightData.setUnit(paramsup.getUnit());
                sysWeightData.setWorkPlanId(sysProductRecord.getWorkPlanId());
                sysWeightData.setProductRecordId(sysProductRecord.getId());
//                    sysWeightData.setId(String.valueOf(paramsup.getId()));
                if (machineName.equals(sysProductRecord.getMachineName())) {
                    log.error("Machine:{}", machineNo);
                    boolean result = this.sysWeightDataService.save(sysWeightData);
                    if (result) {
                        return sysWeightData;
                    }
                } else {
                    return null;
                }

            }
        }
//            break;
        return null;
    }

    public SysProductRecord getWeightDataStart(SysMachinePlc sysMachinePlc, SysProductRecord sysProductRecord) {
        if (sysMachinePlc.isHasWeight()) {
            String weightId1 = null;
            String weightId2 = null;
            if (sysMachinePlc.isHasTwoWeight()) {
                weightId1 = sysMachinePlc.getWeightId1();
                weightId2 = sysMachinePlc.getWeightId2();
            } else {
                weightId2 = "0";
                weightId1 = sysMachinePlc.getWeightId1();
            }
            String sid = this.getSid();
            System.out.println("Sid:" + sid);
            RestTemplate restTemplate = new RestTemplate();
            String machineArea = sysProductRecord.getMachineArea().split("区域")[0];
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_WEIGHT_PLC.NAME.eq(machineArea));
            queryWrapper.limit(1);
            SysWeightPlc sysWeightPlc = this.sysWeightPlcService.getOne(queryWrapper);

            String plcDeviceId = String.valueOf(sysWeightPlc.getDeviceId());
            String baseUrl = "https://api.123321yun.com/device/ex/getDetail?deviceId=%s";
            String url = String.format(baseUrl, plcDeviceId);
            System.out.println("Url:" + url);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
            headers.setContentType(type);
            headers.set("__sid", sid);
            HttpEntity httpEntity = new HttpEntity<>(headers);
            ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, httpEntity, Object.class);
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(responseEntity.getBody());
            System.out.println("Result:" + jsonObject);
            long sleepTime = 10;
            try {
                if (jsonObject.getString("code").equals("200.0")) {
                    SysPlc sysPlc = jsonObject.getObject("data", SysPlc.class);
                    log.error("SYSPLC:{}", sysPlc);
                    JSONArray jsonObject1 = JSON.parseArray(sysPlc.getParamsUp());
                    List<SysWeightData> sysWeightDataList = new ArrayList<>();
                    for (Object object : jsonObject1) {
                        SysWeightData sysWeightData = new SysWeightData();
                        Paramsup paramsup = JSONObject.parseObject(JSONObject.toJSONString(object), Paramsup.class);
                        String machineNo = paramsup.getName().split("#")[0];
                        String machineName = sysWeightPlc.getName() + machineNo;
                        sysWeightData.setMachineName(machineName);
                        sysWeightData.setNum(BigDecimal.valueOf(Double.parseDouble(paramsup.getValue()) ));
                        sysWeightData.setUnit(paramsup.getUnit());
                        sysWeightData.setWorkPlanId(sysProductRecord.getWorkPlanId());
                        sysWeightData.setProductRecordId(sysProductRecord.getId());
//                    sysWeightData.setId(String.valueOf(paramsup.getId()));
                        if (weightId1.equals(machineNo)) {
                            log.error("Machine:{}", machineNo);
                            boolean result = this.sysWeightDataService.save(sysWeightData);
                            if (result) {
                                sysProductRecord.setStartWeight1(BigDecimal.valueOf(Double.parseDouble(paramsup.getValue()) ));
                            }
                        }
                        if (sysMachinePlc.isHasTwoWeight()) {
                            if (weightId2.equals(machineNo)) {
                                boolean result = this.sysWeightDataService.save(sysWeightData);
                                if (result) {
                                    sysProductRecord.setStartWeight2(BigDecimal.valueOf(Double.parseDouble(paramsup.getValue()) ));
                                }
                            }
                        }

                    }
                }
            }catch (Exception e){
                sysProductRecord.setHasWeight(false);
                sysProductRecord.setTwoWeight(false);
            }

        } else {
            sysProductRecord.setHasWeight(false);
            sysProductRecord.setTwoWeight(false);
        }
        return sysProductRecord;
    }
    public SysProductRecord getWeightDataEnd(SysMachinePlc sysMachinePlc, SysProductRecord sysProductRecord) {
        if (sysMachinePlc.isHasWeight()) {
            String weightId1 = null;
            String weightId2 = null;
            if (sysMachinePlc.isHasTwoWeight()) {
                weightId1 = sysMachinePlc.getWeightId1();
                weightId2 = sysMachinePlc.getWeightId2();
            } else {
                weightId2 = "0";
                weightId1 = sysMachinePlc.getWeightId1();
            }
            String sid = this.getSid();
            System.out.println("Sid:" + sid);
            RestTemplate restTemplate = new RestTemplate();
            String machineArea = sysProductRecord.getMachineArea().split("区域")[0];
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_WEIGHT_PLC.NAME.eq(machineArea));
            queryWrapper.limit(1);
            SysWeightPlc sysWeightPlc = this.sysWeightPlcService.getOne(queryWrapper);

            String plcDeviceId = String.valueOf(sysWeightPlc.getDeviceId());
            String baseUrl = "https://api.123321yun.com/device/ex/getDetail?deviceId=%s";
            String url = String.format(baseUrl, plcDeviceId);
            System.out.println("Url:" + url);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
            headers.setContentType(type);
            headers.set("__sid", sid);
            HttpEntity httpEntity = new HttpEntity<>(headers);
            ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, httpEntity, Object.class);
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(responseEntity.getBody());
            System.out.println("Result:" + jsonObject);
            long sleepTime = 10;

            if (jsonObject.getString("code").equals("200.0")) {
                SysPlc sysPlc = jsonObject.getObject("data", SysPlc.class);
                log.error("SYSPLC:{}", sysPlc);
                JSONArray jsonObject1 = JSON.parseArray(sysPlc.getParamsUp());
                List<SysWeightData> sysWeightDataList = new ArrayList<>();
                for (Object object : jsonObject1) {
                    SysWeightData sysWeightData = new SysWeightData();
                    Paramsup paramsup = JSONObject.parseObject(JSONObject.toJSONString(object), Paramsup.class);
                    String machineNo = paramsup.getName().split("#")[0];
                    String machineName = sysWeightPlc.getName() + machineNo;
                    sysWeightData.setMachineName(machineName);
                    sysWeightData.setNum(BigDecimal.valueOf(Double.parseDouble(paramsup.getValue()) ));
                    sysWeightData.setUnit(paramsup.getUnit());
                    sysWeightData.setWorkPlanId(sysProductRecord.getWorkPlanId());
                    sysWeightData.setProductRecordId(sysProductRecord.getId());
//                    sysWeightData.setId(String.valueOf(paramsup.getId()));
                    if (weightId1.equals(machineNo)) {
                        log.error("Machine:{}", machineNo);
                        boolean result = this.sysWeightDataService.save(sysWeightData);
                        if (result) {
                            sysProductRecord.setEndWeight1(BigDecimal.valueOf(Double.parseDouble(paramsup.getValue()) ));
                        }
                    }
                    if (sysMachinePlc.isHasTwoWeight()) {
                        if (weightId2.equals(machineNo)) {
                            boolean result = this.sysWeightDataService.save(sysWeightData);
                            if (result) {
                                sysProductRecord.setEndWeight2(BigDecimal.valueOf(Double.parseDouble(paramsup.getValue()) ));
                            }
                        }
                    }

                }
            }

        } else {
            sysProductRecord.setHasWeight(false);
            sysProductRecord.setTwoWeight(false);
        }
        return sysProductRecord;
    }

}
